<?php

namespace App\Admin\Actions\Member;

use App\Models\yb\UserModel;
use App\Models\yb\UserWalletRecordModel;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;



class ClearPoints extends BatchAction
{
    protected $selector = '.clear-points';

    public $name = "<a class='clear-points btn btn-sm btn-warning' style='margin-left: 5px;'><i class='fa fa-info-circle'></i>&nbsp;清空积分</a>";

    public function handle(Collection $collection)
    {
        try {
            foreach ($collection as $model) {
                $user_data = UserModel::where(['id'=>$model->id])->first();
                UserModel::where(['id'=>$model->id])->update([
                    'surplus_points' => 0,
                ]);
                UserWalletRecordModel::insert([
                    'user_id'=>$user_data['id'],
                    'openid'=>$user_data['openid'],
                    'phone'=>$user_data['phone'],
                    'avatar'=>$user_data['avatar'],
                    'nickname'=>$user_data['nickname'],
                    'amount'=>$user_data['surplus_points'],
                    'status'=>0,
                    'remark'=>'管理员清空积分',
                    'created_at'=>date('Y-m-d H:i:s',time())
                ]);
            }
            return $this->response()->success('操作成功')->refresh();

        } catch (Exception $e) {
            return $this->response()->error('产生错误：'.$e->getMessage());
        }

    }

    public function dialog()
    {
        $this->confirm('您确定清空选中的用户的积分吗？');
    }

}
